// components/providers/auth-provider.tsx
'use client'

import { useEffect } from 'react'
import { useAuthStore } from '@/stores/auth'
import { authService } from '@/services/api/auth'
import { useRouter, usePathname } from 'next/navigation'
import { protectedRoutes, loginRedirect } from '@/assets/static'
import { AUTH_EVENTS, type RedirectEventDetail } from '@/lib/auth-event'
import { useToast } from '@/hooks/use-toast'
import { isDev } from '@/assets/static'

interface AuthProviderProps {
  children: React.ReactNode
}

export function AuthProvider({ children }: AuthProviderProps) {
  const { token, setAuth, _hasHydrated } = useAuthStore()
  const router = useRouter()
  const pathname = usePathname()
  const { toast } = useToast()

  // 在应用启动时验证 token
  useEffect(() => {
    if (isDev) {
      ;(window as any).router = router
    }
    const validateAuth = async () => {
      if (token) {
        try {
          authService.getAuthList()
          const user = await authService.getCurrentUser()
          setAuth(token, user)
        } catch (error) {
          console.error(
            '🚀 ~ validateAuth ~ error:',
            error,
            useAuthStore.getState().token,
          )

          toast({
            variant: 'destructive',
            description: '登录已过期，请重新登录',
            duration: 3000,
          })
          // Token 无效，清除认证信息
          useAuthStore.getState().clearAuth()
          if (isDev) {
            setTimeout(() => {
              // 弹出弹框，填写 token
              const newToken = prompt('请输入 token')
              if (newToken) {
                setAuth(newToken, null)
                router.push('/movie')
              }
            }, 100)
          }
        }
      }
    }

    validateAuth()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, setAuth])

  // 路由守卫
  useEffect(() => {
    // 只在未登录时拦截受保护的路由
    if (!_hasHydrated) {
      return
    }
    const isProtectedRoute = protectedRoutes.some((route) =>
      pathname.startsWith(route),
    )
    if (!token && isProtectedRoute) {
      router.push(`${loginRedirect}?from=${pathname}`)
    }
  }, [token, _hasHydrated, pathname, router])

  useEffect(() => {
    const handleRedirect = (event: CustomEvent<RedirectEventDetail>) => {
      const { path, from } = event.detail
      const redirectUrl = from ? `${path}?from=${encodeURIComponent(from)}` : path
      const currentPath = decodeURIComponent(location.href).replace(
        location.origin,
        '',
      )
      if (currentPath === redirectUrl) {
        return
      }
      console.log('重定向', redirectUrl)
      router.push(redirectUrl)
      router.refresh()
    }

    window.addEventListener(
      AUTH_EVENTS.REDIRECT_NEEDED,
      handleRedirect as EventListener,
    )

    return () => {
      window.removeEventListener(
        AUTH_EVENTS.REDIRECT_NEEDED,
        handleRedirect as EventListener,
      )
    }
  }, [router, pathname])

  return <>{children}</>
}
